﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Threading;
using System.IO;
using System.Data.OleDb;
using System.Data;


namespace LxjCommon
{
    public class MyImage
    {
        #region 网站路径
        private string PhysicalAppPath;
        /// <summary>
        /// 获取应用程序物理根路径
        /// </summary>
        public string PhysicalApplicationPath
        {
            get
            {
                GetPhysicalApplicationPath();
                return PhysicalAppPath;
            }
        }
        private void GetPhysicalApplicationPath()
        {
            if (PhysicalAppPath == null)
            {
                PhysicalAppPath = HttpContext.Current.Request.PhysicalApplicationPath;
            }
        }

        private string AppPath;
        /// <summary>
        /// 获取应用程序虚拟根路径
        /// </summary>
        public string ApplicationPath
        {
            get
            {
                GetApplicationPath();
                return AppPath;
            }
        }
        private void GetApplicationPath()
        {
            if (AppPath == null)
            {
                AppPath = HttpContext.Current.Request.ApplicationPath == "/" ? null : HttpContext.Current.Request.ApplicationPath;
            }
        }
        #endregion
        #region 上传图片
        /// <summary>
        /// 截取图片后缀名
        /// </summary>
        /// <param name="hifile"></param>
        /// <returns></returns>
        public string GetFileType(FileUpload hifile)
        {
            if (hifile.HasFile)
            {
                string fileName = hifile.PostedFile.FileName;
                return fileName.Substring(fileName.LastIndexOf("."));
            }
            return null;
        }

        /// <summary>
        /// 是否允许该扩展名上传（广告）
        /// </summary>
        /// <param name="hifile">HtmlInputFile控件</param>
        /// <returns>允许则返回true,否则返回false</returns>
        public bool IsAllowedVedio(FileUpload hifile)
        {
            string strOldFilePath = "", strExtension = "";

            //允许上传的扩展名，可以改成从配置文件中读出
            string[] arrExtension = { ".mp3", ".rm", ".rmvb", ".mp4" };

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.ToLower().Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 是否允许该扩展名上传（广告）
        /// </summary>
        /// <param name="hifile">HtmlInputFile控件</param>
        /// <returns>允许则返回true,否则返回false</returns>
        public bool IsAllowedExtensionAD(FileUpload hifile)
        {
            string strOldFilePath = "", strExtension = "";

            //允许上传的扩展名，可以改成从配置文件中读出
            string[] arrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png", ".swf" };

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.ToLower().Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 是否允许该扩展名上传（文件）
        /// </summary>
        /// <param name="hifile">HtmlInputFile控件</param>
        /// <returns>允许则返回true,否则返回false</returns>
        public bool IsAllowedExtensionFile(FileUpload hifile)
        {
            string strOldFilePath = "", strExtension = "";

            //允许上传的扩展名，可以改成从配置文件中读出
            string[] arrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png", ".swf" };

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.ToLower().Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 是否允许该扩展名上传（图片）
        /// </summary>
        /// <param name="hifile"></param>
        /// <returns></returns>
        public bool IsAllowedExtension(FileUpload hifile)
        {
            string strOldFilePath = "", strExtension = "";

            //允许上传的扩展名，可以改成从配置文件中读出
            string[] arrExtension = { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.ToLower().Equals(arrExtension[i]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }



        /// <summary>
        /// 缩放图片带水印
        /// </summary>
        /// <param name="hifile"></param>
        /// <param name="imgName"></param>
        /// <param name="aWidth"></param>
        /// <param name="aHeight"></param>
        /// <param name="sUrl"></param>
        /// <returns></returns>
        public string UpImages(FileUpload hifile, string imgName, Unit aWidth, Unit aHeight, string sUrl)
        {
            string strOldFilePath = hifile.PostedFile.FileName;
            //取得上传文件的扩展名
            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            //生成原图 
            Byte[] oFileByte = new byte[hifile.PostedFile.ContentLength];
            System.IO.Stream oStream = hifile.PostedFile.InputStream;
            System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

            int oWidth = oImage.Width; //原图宽度 
            int oHeight = oImage.Height; //原图高度 
            int tWidth = Convert.ToInt32(aWidth.Value); //设置缩略图初始宽度 
            int tHeight = Convert.ToInt32(aHeight.Value); //设置缩略图初始高度


            if (imgName == "")
            {
                //图片名
                imgName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + strExtension;
                //图片存储相对路径
            }
            string path = PhysicalApplicationPath + "/UpImage/" + imgName;
            if (oWidth <= tWidth && oHeight <= tHeight)
            {
                try
                {
                    hifile.PostedFile.SaveAs(path);
                }
                catch
                {
                    imgName = "no";
                }
            }
            else
            {
                //按比例计算出缩略图的宽度和高度 
                if (oWidth >= oHeight)
                {
                    tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                }
                else
                {
                    tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                }

                //生成缩略原图 
                Bitmap tImage = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 
                g.Clear(Color.Transparent); //清空画布并以透明背景色填充 
                g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);

                //logo上填充文字

                Font textFont = new Font("arial", 16, FontStyle.Bold);


                //第一个参数是离图片最右边的距离,正数为图片右边往右开始算,负数从图片右边往左算
                //第二个参数设置图片距离上边的距离,正数为图片上边往下开始算,负数从图片上边网上开始算
                //其他参数没试过

                RectangleF rectangle = new RectangleF(tImage.Width / (-3), tImage.Height / 2, tImage.Width, tImage.Height / 5);

                StringFormat StrFormat = new StringFormat();
                StrFormat.Alignment = StringAlignment.Far;

                g.DrawString(sUrl, textFont, new SolidBrush(Color.FromArgb(153, 0, 0, 0)), rectangle, StrFormat);
                SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(150, 255, 255, 255)); //设透明字体 第一个参数越小越透明
                g.DrawString(sUrl, textFont, semiTransBrush, rectangle, StrFormat);


                g.DrawImage(tImage, new Rectangle(tImage.Width, tImage.Height, tImage.Width, tImage.Height), 0, 0, tImage.Width, tImage.Height, GraphicsUnit.Pixel);


                g.Dispose();


                //存储图片所需的绝对路径
                try
                {
                    //以JPG格式保存图片 
                    tImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch
                {
                    imgName = "no";
                }
                finally
                {
                    //释放资源 
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }
            return imgName;
        }

        /// <summary>
        /// 缩放图片不带水印
        /// </summary>
        /// <param name="hifile"></param>
        /// <param name="imgName"></param>
        /// <param name="aWidth"></param>
        /// <param name="aHeight"></param>
        /// <returns></returns>
        public string UpImages(FileUpload hifile, string imgName, Unit aWidth, Unit aHeight)
        {
            string strOldFilePath = hifile.PostedFile.FileName;
            //取得上传文件的扩展名
            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            //生成原图 
            Byte[] oFileByte = new byte[hifile.PostedFile.ContentLength];
            System.IO.Stream oStream = hifile.PostedFile.InputStream;
            System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

            int oWidth = oImage.Width; //原图宽度 
            int oHeight = oImage.Height; //原图高度 
            int tWidth = Convert.ToInt32(aWidth.Value); //设置缩略图初始宽度 
            int tHeight = Convert.ToInt32(aHeight.Value); //设置缩略图初始高度


            //一下代码仅针对320*480或者480*320的图片上传处理纵向和横向
            if (((tWidth == 480) && (tHeight == 320)) || (tWidth == 320) && (tHeight == 480))
            {
                if (((oWidth > oHeight) && (tWidth < tHeight)) || ((oWidth < oHeight) && (tWidth > tHeight)))
                {
                    int temp = tWidth;
                    tWidth = tHeight;
                    tHeight = temp;
                }
            }

            if (imgName == "")
            {
                //图片名
                Thread.Sleep(100);
                imgName = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + strExtension;
                //图片存储相对路径
            }

            string path = PhysicalApplicationPath + "/Manage/custom/UpImage/" + imgName;
            string Phpath = PhysicalApplicationPath + "/Manage/custom/UpImage/" + DateTime.Now.ToString("yyyyMM") + "/";
            if (oWidth <= tWidth && oHeight <= tHeight)
            {
                try
                {
                    if (!Directory.Exists(Phpath))
                        Directory.CreateDirectory(Phpath);
                    hifile.PostedFile.SaveAs(path);
                }
                catch
                {
                    imgName = "no";
                }
            }
            else
            {
                //按比例计算出缩略图的宽度和高度 
                if (oWidth >= oHeight)
                {
                    tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                }
                else
                {
                    tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                }

                //生成缩略原图 
                Bitmap tImage = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 
                g.Clear(Color.Transparent); //清空画布并以透明背景色填充 


                g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);

                //存储图片所需的绝对路径
                try
                {
                    if (!Directory.Exists(Phpath))
                        Directory.CreateDirectory(Phpath);
                    //以JPG格式保存图片 
                    tImage.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                }
                catch
                {
                    imgName = "no";
                }
                finally
                {
                    //释放资源 
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }
            return imgName;
        }

        /// <summary>
        /// 缩放图片不带水印
        /// </summary>
        /// <param name="hifile"></param>
        /// <param name="imgName"></param>
        /// <param name="aWidth"></param>
        /// <param name="aHeight"></param>
        /// <returns></returns>
        public string UpIcos(FileUpload hifile, string imgName, Unit aWidth, Unit aHeight)
        {
            string strOldFilePath = hifile.PostedFile.FileName;
            //取得上传文件的扩展名
            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            //生成原图 
            Byte[] oFileByte = new byte[hifile.PostedFile.ContentLength];
            System.IO.Stream oStream = hifile.PostedFile.InputStream;
            System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

            int oWidth = oImage.Width; //原图宽度 
            int oHeight = oImage.Height; //原图高度 
            int tWidth = Convert.ToInt32(aWidth.Value); //设置缩略图初始宽度 
            int tHeight = Convert.ToInt32(aHeight.Value); //设置缩略图初始高度


            if (imgName == "")
            {
                //图片名
                Thread.Sleep(100);
                imgName = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + strExtension;
                //图片存储相对路径
            }

            string path = PhysicalApplicationPath + "/UpImage/" + imgName;
            if (oWidth <= tWidth && oHeight <= tHeight)
            {
                try
                {
                    hifile.PostedFile.SaveAs(path);
                }
                catch
                {
                    imgName = "no";
                }
            }
            else
            {
                //按比例计算出缩略图的宽度和高度 
                if (oWidth >= oHeight)
                {
                    tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                }
                else
                {
                    tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                }

                //生成缩略原图 
                Bitmap tImage = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 
                g.Clear(Color.Transparent); //清空画布并以透明背景色填充 


                g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);

                //存储图片所需的绝对路径
                try
                {
                    //以JPG格式保存图片 
                    tImage.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                }
                catch
                {
                    imgName = "no";
                }
                finally
                {
                    //释放资源 
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }
            return imgName;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="hifile"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public string UpImages(FileUpload hifile, string folder)
        {
            string strOldFilePath = hifile.PostedFile.FileName;
            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            string str = PhysicalApplicationPath + "/Manage/custom/UpExcel/" + DateTime.Now.ToString("yyyyMM") + "/";
            string fileType = this.GetFileType(hifile);
            string sStr = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
            if (folder == "")
            {
                str = str + sStr;
            }
            else
            {
                str = str + folder;
                sStr = folder;
            }

            try
            {
                if (!Directory.Exists(PhysicalApplicationPath + "/Manage/custom/UpExcel/" + DateTime.Now.ToString("yyyyMM") + "/"))
                    Directory.CreateDirectory(PhysicalApplicationPath + "/Manage/custom/UpExcel/" + DateTime.Now.ToString("yyyyMM") + "/");
                hifile.PostedFile.SaveAs(str);
                return sStr;
            }
            catch (Exception ex)
            {
                string sError = ex.ToString();
                return "no";
            }
        }

        public string UpImages(FileUpload hifile, string folder, string sPath)
        {
            string strOldFilePath = hifile.PostedFile.FileName;
            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            string str = PhysicalApplicationPath + "/UpImage/" + sPath + "/";
            string fileType = this.GetFileType(hifile);

            string sStr = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;

            if (folder != "")
            {
                str = str + folder;
                sStr = folder;

            }
            else
            {
                str = str + sStr;

            }

            try
            {
                hifile.PostedFile.SaveAs(str);
                return sStr;
            }
            catch (Exception ex)
            {
                string sError = ex.ToString();
                return "no";
            }
        }

        public string UserUpImages(FileUpload hifile, string folder)
        {
            string str = PhysicalApplicationPath + folder;
            string fileType = this.GetFileType(hifile);
            string imgname = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType;
            string str3 = "/Manage/custom/UpImage/" + imgname;
            try
            {
                if (!Directory.Exists(PhysicalApplicationPath + "/Manage/custom/UpImage/" + DateTime.Now.ToString("yyyyMM") + "/"))
                    Directory.CreateDirectory(PhysicalApplicationPath + "/Manage/custom/UpImage/" + DateTime.Now.ToString("yyyyMM") + "/");
                hifile.PostedFile.SaveAs(str + str3);
                return imgname;
            }
            catch
            {
                return "no";
            }
        }

        public string UserUpImages(FileUpload hifile, string imgName, string user_id, Unit aWidth, Unit aHeight)
        {
            string strOldFilePath = hifile.PostedFile.FileName;
            //取得上传文件的扩展名
            string strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
            //生成原图 
            Byte[] oFileByte = new byte[hifile.PostedFile.ContentLength];
            System.IO.Stream oStream = hifile.PostedFile.InputStream;
            System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

            int oWidth = oImage.Width; //原图宽度 
            int oHeight = oImage.Height; //原图高度 
            int tWidth = Convert.ToInt32(aWidth.Value); //设置缩略图初始宽度 
            int tHeight = Convert.ToInt32(aHeight.Value); //设置缩略图初始高度
            if (imgName == "")
            {
                //图片名
                imgName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + strExtension;
                //图片存储相对路径
            }
            string path = HttpContext.Current.Server.MapPath("../UpImage/user/") + user_id + "/" + imgName;
            if (oWidth <= tWidth && oHeight <= tHeight)
            {
                try
                {
                    hifile.PostedFile.SaveAs(path);
                }
                catch
                {
                    imgName = "no";
                }
            }
            else
            {
                //按比例计算出缩略图的宽度和高度 
                if (oWidth >= oHeight)
                {
                    tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
                }
                else
                {
                    tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
                }

                //生成缩略原图 
                Bitmap tImage = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(tImage);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度 
                g.Clear(Color.Transparent); //清空画布并以透明背景色填充 
                g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);




                //存储图片所需的绝对路径
                try
                {
                    //以JPG格式保存图片 
                    tImage.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch
                {
                    imgName = "no";
                }
                finally
                {
                    //释放资源 
                    oImage.Dispose();
                    g.Dispose();
                    tImage.Dispose();
                }
            }
            return imgName;
        }
        #endregion
    }
}
